package cn.edu.sjtu.se.peakfactory.dao.impls.hibernate;

import java.util.Date;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import cn.edu.sjtu.se.lchang.socialnetwork.dao.bean.User;
import cn.edu.sjtu.se.lchang.socialnetwork.dao.impls.hibernate.BaseDAOImpl;
import cn.edu.sjtu.se.peakfactory.dao.bean.Coupon;
import cn.edu.sjtu.se.peakfactory.dao.bean.UserCoupon;
import cn.edu.sjtu.se.peakfactory.dao.interfaces.UserCouponDAO;

public class UserCouponDAOImpl extends BaseDAOImpl<UserCoupon> implements UserCouponDAO {

	public List<UserCoupon> getUserCoupons(Long userId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserCoupon.class);
		criteria.add(Restrictions.eq("user.id", userId));
		return findByCriteria(criteria);
	}

	public UserCoupon getUserCouponsById(Long userId, Long couponId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserCoupon.class);
		criteria.add(Restrictions.eq("user.id", userId)).add(Restrictions.eq("coupon.id", couponId));
		List<UserCoupon> result = findByCriteria(criteria);
		if (result != null && !result.isEmpty()) {
			return result.get(0);
		}
		return null;
	}

	public Long gainUserCoupon(Long userId, Long couponId, Date startTime) {
		UserCoupon userCoupon = new UserCoupon();
		User user = new User();
		user.setId(userId);
		Coupon coupon = new Coupon();
		coupon.setId(couponId);
		userCoupon.setUser(user);
		userCoupon.setCoupon(coupon);
		userCoupon.setGetTime(startTime);
		return save(userCoupon);
	}

	public int useUserCoupon(Long userId, Long couponId, Date endTime) {
		org.hibernate.Query query = getHibernateSession().createQuery(
				"update UserCoupon set useTime = ? where user.id =? and coupon.id=?");
		query.setParameter(0, endTime);
		query.setParameter(1, userId);
		query.setParameter(2, couponId);
		return query.executeUpdate();
	}

}
